package com.watersys.httpserver;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.protocol.HTTP;
 
/**
 * �������д����ֽ���������Ҫ��ʵ��ProgressListener�е�trasnfered()���������н����
 * @author king
 *
 */
public class CustomMultiPartEntity extends MultipartEntity
{
 
	private  ProgressListener listener;
 
	public CustomMultiPartEntity( ProgressListener listener)
	{
		super();
		this.listener = listener;
	}
 
	public CustomMultiPartEntity( HttpMultipartMode mode,  ProgressListener listener)
	{
		super(mode);
		this.listener = listener;
	}
 
	public CustomMultiPartEntity(HttpMultipartMode mode,  String boundary,  Charset charset,  ProgressListener listener)
	{
		super(mode, boundary, charset);
		this.listener = listener;
	}
 
	@Override
	public void writeTo(final OutputStream outstream) throws IOException
	{
		super.writeTo(new CountingOutputStream(outstream, this.listener));
	}
 
	public static interface ProgressListener
	{
		void transferred(long num);
	}
 
	public static class CountingOutputStream extends FilterOutputStream
	{
 
		private final ProgressListener listener;
		private long transferred;
 
		public CountingOutputStream(final OutputStream out, final ProgressListener listener)
		{
			super(out);
			this.listener = listener;
			this.transferred = 0;
			//UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
		}
 
		public void write(byte[] b, int off, int len) throws IOException
		{
			out.write(b, off, len);
			this.transferred += len;
			this.listener.transferred(this.transferred);
		}
 
		public void write(int b) throws IOException
		{
			out.write(b);
			this.transferred++;
			this.listener.transferred(this.transferred);
		}
	}


}
